import { defineStore } from 'pinia';
import { ref, computed } from 'vue';
import { getCurrentUserInfo } from '../server/api';
import type { LoginParams, UserInfo } from '../server/type';

/**
 * 用户状态管理
 */
export const useUserStore = defineStore('user', () => {
  // 用户信息
  const userInfo = ref<UserInfo | null>(null);
  
  // tsToken
  const tsToken = ref<string>('');
  
  // 是否已登录
  const isLoggedIn = computed(() => !!tsToken.value && !!userInfo.value);
  
  // 用户角色
  const userRole = computed(() => userInfo.value?.role || '');
  
  // 用户权限
  const userPermissions = computed(() => userInfo.value?.permissions || []);

  /**
   * 登录
   */
  const login = async (params: LoginParams): Promise<void> => {
    try {
      // 保存tsToken到localStorage，用于API请求
      localStorage.setItem('tsToken', params.tsToken);
      
      // 调用getCurrentUserInfo验证tsToken并获取用户信息
      const result = await getCurrentUserInfo();
      console.log('获取用户信息结果:', result);
      // @ts-ignore
      if (result.success) {
        // 保存tsToken
        tsToken.value = params.tsToken;
        localStorage.setItem('tsToken', params.tsToken);
        
        // 保存用户信息
        userInfo.value = result.result;
        localStorage.setItem('userInfo', JSON.stringify(result.result));
        
        console.log('登录成功，用户信息:', result.result);
      } else {
        throw new Error(result.message || '获取用户信息失败');
      }
      
    } catch (error) {
      console.error('登录失败:', error);
      // 清除可能已保存的数据
      localStorage.removeItem('tsToken');
      localStorage.removeItem('userInfo');
      throw error;
    }
  };

  /**
   * 登出
   */
  const logout = (): void => {
    // 清除状态
    tsToken.value = '';
    userInfo.value = null;
    
    // 清除本地存储
    localStorage.removeItem('tsToken');
    localStorage.removeItem('userInfo');
  };

  /**
   * 获取用户信息
   */
  const fetchUserInfo = async (): Promise<void> => {
    try {
      if (!tsToken.value) {
        throw new Error('未登录');
      }
      
      const result = await getCurrentUserInfo();
      if (result.code === 200 && result.data) {
        userInfo.value = result.data;
        localStorage.setItem('userInfo', JSON.stringify(result.data));
      } else {
        throw new Error(result.message || '获取用户信息失败');
      }
      
    } catch (error) {
      console.error('获取用户信息失败:', error);
      // 如果获取用户信息失败，清除登录状态
      logout();
      throw error;
    }
  };

  /**
   * 初始化用户状态（从本地存储恢复）
   */
  const initUserState = (): void => {
    const savedTsToken = localStorage.getItem('tsToken');
    const savedUserInfo = localStorage.getItem('userInfo');
    
    if (savedTsToken && savedUserInfo) {
      tsToken.value = savedTsToken;
      userInfo.value = JSON.parse(savedUserInfo);
    }
  };

  /**
   * 检查用户权限
   */
  const hasPermission = (permission: string): boolean => {
    if (!userInfo.value) return false;
    return userPermissions.value.includes(permission);
  };

  /**
   * 检查用户角色
   */
  const hasRole = (role: string): boolean => {
    if (!userInfo.value) return false;
    return userRole.value === role;
  };

  /**
   * 更新用户信息
   */
  const updateUserInfo = (newUserInfo: Partial<UserInfo>): void => {
    if (userInfo.value) {
      userInfo.value = { ...userInfo.value, ...newUserInfo };
      localStorage.setItem('userInfo', JSON.stringify(userInfo.value));
    }
  };

  return {
    // 状态
    userInfo,
    tsToken,
    isLoggedIn,
    userRole,
    userPermissions,
    
    // 方法
    login,
    logout,
    fetchUserInfo,
    initUserState,
    hasPermission,
    hasRole,
    updateUserInfo
  };
});
